from datetime import datetime
from models import LogEntry
from google.appengine.api.labs import taskqueue

class Logger (object):
    """The public logger interface.

    This is the class to access the logger functionality.

    This implementation is also used for the JSON-RPC interface using
    lovely.jsonrpc. Every method not starting with an '_' will be a public
    JSON-RPC method.
    If private functions are needed they must start with an '_'.
    """

    max_count = 400
    all_fields = ['eventtype', 'context', 'domain', 'msg_key',
                  'msg_value', 'timestamp']

    def log(self, domain, context, msg_key=None, msg_value=None,
            timestamp=None, eventtype='info'):

        if timestamp is None:
            timestamp = datetime.now()

        entry = LogEntry(domain=domain, context=context, msg_key=msg_key,
                         msg_value=msg_value, timestamp=timestamp,
                         eventtype=eventtype)
        entry.put()

        taskqueue.add(url='/worker', params={
            'timestamp' : timestamp,
            'domain' : domain,
            'context' : context,
            'msg_key' : msg_key,
            'msg_value' : msg_value,
            'eventtype' : eventtype
            })

        return True

    def query(self, filters=None, order=None, limit=10, offset=0, fields=None):
        count, objects = self._query(filters, order, limit, offset, fields)
        if fields is None:
            fields = self.all_fields
        data = [self._o2json(o, fields=fields) for o in objects]
        return dict(totalLength=count,
                    data=data,
                   )

    def _query(self, filters, order, limit, offset, fields):
        q = LogEntry.all()
        if order is not None:
            q.order(order)
        if filters:
            for po, value in filters:
                q.filter(po, value)
        return q.count(self.max_count), q.fetch(limit, offset=offset)

    def _o2json(self, o, fields):
        return dict([(f, getattr(o, f)) for f in fields])


